// data([{shoeSize: 40}]).where("shoeSize").equals(40).toArray()

function data(data) {
  return new Data(data)
}

function Data(data) {
  this.data = data
}

Data.prototype.where = function (input) {
  return new WhereClause(this.data, input)
};

Data.prototype.add = function (value) {
  this.data.push(value);
  return this.data;
};

function matched(item, value) {
  return Object.keys(value).every(key => item[key] === value[key]);
}

Data.prototype.update = function (target, value) {
  return this.data.reduce((pre, cur) => {
    let result = cur;
    if(matched(cur, target)) {
      result = {...cur, ...value}
    }
    return [...pre, result]
  }, []);
};

function WhereClause(data, index) {
  this.data = data;
  this.index = index;
}

WhereClause.prototype.equals = function (value) {
  const data = this.data;
  const index = this.index;
  return new Collection(this, function () {
    return data.filter(d => d[index] === value)
  })
};

function Collection(whereClause, dataGenerator) {
  this.data = whereClause.data;
  this.dataGenerator = dataGenerator
}

Collection.prototype.toArray = function () {
  if (this.dataGenerator) {
    return this.dataGenerator()
  }
  return this.data
};

Collection.prototype.limit = function (end) {
  this.dataGenerator = undefined;
  this.data = this.data.slice(0, end);
  return this
};

console.log(data([{shoeSize: 40, name: '123'}, {shoeSize: 40}]).where('shoeSize').equals(40).toArray(), '结果');
console.log(data([{shoeSize: 40, name: '123'}, {shoeSize: 40}]).where('shoeSize').equals(40).limit(1).toArray(), '结果');
// console.log(data([{shoeSize: 40}]).add(1));
// console.log(data([{shoeSize: 30, name: '123'}, {shoeSize: 30}, {shoeSize: 50}]).update({shoeSize: 30, name: '123'}, {shoeSize: 50}));




